package com.apes.fn.scm.used.server;

import com.alibaba.fastjson.JSONObject;
import com.apes.fn.scm.retailOrder.service.tc.TCService;
import com.apes.fn.scm.settleCheck.model.PartnerCheckCreate;
import com.apes.fn.scm.used.model.UsedCar;
import com.apes.fn.scm.used.repository.UsedCarRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.repository.CustomRepository;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.outbox.OutboxEventService;
import com.apes.framework.plugin.outbox.OutboxPayloadWrapper;
import com.apes.framework.plugin.outbox.annotation.OutboxSubscriber;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.hr.base.model.WorkPost;
import com.apes.hr.base.repository.WorkPostRepository;
import com.apes.scm.masterdata.car.model.CarConfiguration;
import com.apes.scm.masterdata.car.model.CarModel;
import com.apes.scm.masterdata.car.repository.CarConfigurationRepository;
import com.apes.scm.masterdata.car.repository.CarModelRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("usedCarService")
public class UsedCarService extends DomainService {

    @Autowired
    UsedCarRepository usedCarRepository;
    @Autowired
    EnumerationRepository enumerationRepository;
    @Autowired
    WorkPostRepository workPostRepository;
    @Autowired
    UserRepository userRepository;
    @Autowired
    CarModelRepository carModelRepository;
    @Autowired
    CarConfigurationRepository carConfigurationRepository;

    /***
     * 创建
     */
    public UsedCar create(SimpleRequest request) {
        UsedCar UsedCar = request.getO(UsedCar.class);
        List<CarModel> carModels = carModelRepository.findAll(JpaDsl.toCriteria(
                "name", "EQ", UsedCar.getJekunCarModel()
        ));
        List<CarConfiguration> carConfigurations = carConfigurationRepository.findAll(JpaDsl.toCriteria(
                "name", "EQ", UsedCar.getCarModelLabelName()
        ));
        if (carModels != null && carModels.size() == 1)
            UsedCar.setCarModel(carModels.get(0));
        if (carConfigurations != null && carConfigurations.size() == 1)
            UsedCar.setCarModelLabel(carConfigurations.get(0));
        UsedCar.setState("create");
        UsedCar.setCompany(UsedCar.getDept().getCompany());
        UsedCar.setDateCreate(new Date());
        UsedCar.setCreateUID(getPerson(request));
        return usedCarRepository.saveAndFlush(UsedCar);
    }

    /***
     * 修改
     */
    public UsedCar update(SimpleRequest request) {
        isValid(request, usedCarRepository);
        UsedCar UsedCar = request.getO(UsedCar.class);
        return usedCarRepository.saveAndFlush(UsedCar);
    }


    /***
     * 删除
     */
    public String delete(SimpleRequest request) {
        isValid(request, usedCarRepository);
        UsedCar UsedCar = request.getO(UsedCar.class);
        UsedCar.setState("delete");
        usedCarRepository.saveAndFlush(UsedCar);
        //        usedCarRepository.delete(UsedCar);
        return "删除成功！";
    }

    /***
     * 审批
     */
    public UsedCar approve(SimpleRequest request) {
        UsedCar UsedCar = request.getO(UsedCar.class);
        UsedCar.setState("approve");
        UsedCar.setDateApprove(new Date());
        UsedCar.setApproveUID(getPerson(request));
        commission(UsedCar);
        //推送计算平台管理费
//        pushMessageForCalculateFee(UsedCar);
        //直接计算平台管理费
        calculatePlatformManagementFee(UsedCar);

        return usedCarRepository.saveAndFlush(UsedCar);
    }
    /***
     * 审批
     * "createDate","GTE",startDate,"createDate","LTE",endDate
     */
    public void test(SimpleRequest request) {
        List<UsedCar> cars = usedCarRepository.findAll(JpaDsl.toCriteria(
                "createDate", "GTE", DateUtil.parse("2023-09-01", DateUtil.SHOW_DATE_FORMAT),
                "createDate", "LTE", DateUtil.parse("2023-10-01", DateUtil.SHOW_DATE_FORMAT)
        ));
        for (UsedCar car : cars) {
            calculatePlatformManagementFee(car);
            usedCarRepository.saveAndFlush(car);
        }


    }

    private void calculatePlatformManagementFee(UsedCar usedCar) {
        PartnerCheckCreate partnerCheckCreate = new PartnerCheckCreate();
        List<Map> items = new ArrayList();
        items.add(MapUtil.mapper(
                "cost", usedCar.getStorePrice(),
                "classifyId", null,
                "companyId", usedCar.getCompany().getId()
        ));

        partnerCheckCreate.getFee(items, PartnerCheckCreate.Type.UsedCar);

        items.forEach( item -> {
            usedCar.setPlatformManagementFee( item.get("platformManagementFee") != null ?  ((double) item.get("platformManagementFee")) : 0.0);
        });
        usedCar.setCalculateFlag(true);
    }

    /**
     * 提成计算规则
     *
     * @param usedCar
     */
    public void commission(UsedCar usedCar) {
        double storePrice = usedCar.getStorePrice();
        Dept dept = usedCar.getDept();
        WorkPost workPost = workPostRepository.findOne("0000016");
        Enumeration oneNode = enumerationRepository.findByTypeAndValue("001", "usedCarCommission");
        double oneNodeD = Double.valueOf(oneNode.getCode()); //第一节点比较金额
        Enumeration twoNode = enumerationRepository.findByTypeAndValue("002", "usedCarCommission");
        double twoNodeD = Double.valueOf(twoNode.getCode()); //第二节点比较金额
        Enumeration commissionBase = enumerationRepository.findByTypeAndValue("003", "usedCarCommission");
        double commissionBaseD = Double.valueOf(commissionBase.getCode()); //得出提成基数的比例
        Enumeration followProportion = enumerationRepository.findByTypeAndValue("004", "usedCarCommission");
        double followProportionD = Double.valueOf(followProportion.getCode()); //跟进人提成比例
        Enumeration inspectorProportion = enumerationRepository.findByTypeAndValue("005", "usedCarCommission");
        double inspectorProportionD = Double.valueOf(inspectorProportion.getCode()); //检测师提成比例
        Enumeration storeManagerProportion = enumerationRepository.findByTypeAndValue("006", "usedCarCommission");
        double storeManagerProportionD = Double.valueOf(storeManagerProportion.getCode()); //店长提成比例
        com.apes.framework.plugin.workflow.parser.model.User user = new com.apes.framework.plugin.workflow.parser.model.User();
        List<Map> mapList = user.getUsersRecursiveByWorkPost(dept.getBranch(), workPost);
        if (mapList != null && !mapList.isEmpty()) {
            Map map = mapList.get(0);
            User user1 = userRepository.findOne((Integer) map.get("id"));
            usedCar.setStoreManagerId(user1.getPerson());
        }
        double storeManager = 0; //店长提成
        double follow = 0;       // 跟进人提成
        double inspector = 0;   //检测师提成
        double newStorePrice = storePrice * commissionBaseD; //二手车服务费*10%
        if (storePrice >= oneNodeD) {
            storeManager = oneNodeD * storeManagerProportionD;
            if (newStorePrice >= twoNodeD) {
                follow = newStorePrice * followProportionD;
                inspector = newStorePrice * inspectorProportionD;
            } else {
                follow = twoNodeD * followProportionD;
                inspector = twoNodeD * inspectorProportionD;
            }
        } else {
            follow = 100 * followProportionD;
            inspector = 100 * inspectorProportionD;
        }
        usedCar.setStoreManager(storeManager);
        usedCar.setFollowCommission(follow);
        usedCar.setInspectorCommission(inspector);

    }

    /***
     * 数据是否合法
     * @param request
     * @param repository
     */
    private Model isValid(SimpleRequest request, CustomRepository repository) {
        Model oldModel = (Model) repository.findOne((String) request.get("id"));
        if (oldModel == null) throw new RuntimeException("编码【" + request.get("id") + "】在系统中不存在。");
        if (oldModel.getVersion() != (int) request.get("version")) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        return oldModel;
    }


    @OutboxSubscriber(id = "fn.usedCar.commission", name = "审核写提成", condition = " dateApprove != null && state == 'approve' ")
    public void inCommissionBySubmitToEmp(UsedCar usedCar) {
        PartyRole role = usedCar.getDept().getCompany();
        JSONObject json = new JSONObject();
        json.put("TJRQ", usedCar.getDateApprove());
        json.put("DEPT_ID", usedCar.getDept().getId());
        json.put("DEPT_NAME", usedCar.getDept().getName());
        json.put("COMPANY_ID", role.getId());
        json.put("COMPANY_NAME", role.getName());
        json.put("USED_CAR_FINAL_PRICE", usedCar.getFinalPrice());//成交价
        json.put("USED_CAR_PRICE", usedCar.getStorePrice());//门店服务费
        // 检测师
        if (usedCar.getInspectorId() != null) {
            json.put("EMPLOYEE_ID", usedCar.getInspectorId().getId());
            json.put("EMPLOYEE_NAME", usedCar.getInspectorId().getName());
            json.put("USED_CAR_FINAL_PRICE_TC", usedCar.getInspectorCommission());
            SpringManager.getBean(TCService.class).inCommissionBySubmitToEmp(json);
        }
        // 店长
        if (usedCar.getStoreManagerId() != null) {
            json.put("EMPLOYEE_ID", usedCar.getStoreManagerId().getId());
            json.put("EMPLOYEE_NAME", usedCar.getStoreManagerId().getName());
            json.put("USED_CAR_FINAL_PRICE_TC", usedCar.getStoreManager());
            SpringManager.getBean(TCService.class).inCommissionBySubmitToEmp(json);
        }
        // 跟进人
        if (usedCar.getFollowId() != null) {
            json.put("EMPLOYEE_ID", usedCar.getFollowId().getId());
            json.put("EMPLOYEE_NAME", usedCar.getFollowId().getName());
            json.put("USED_CAR_FINAL_PRICE_TC", usedCar.getFollowCommission());
            SpringManager.getBean(TCService.class).inCommissionBySubmitToEmp(json);
        }
    }

    @OutboxSubscriber(id = "fn.usedcar.inspectorCommission", name = "审核写检测提成", condition = " dateApprove != null && state == 'approve' && inspectorId != null ")
    public void inspectorCommissionBySubmit(UsedCar usedCar) {
        PartyRole role = usedCar.getDept().getCompany();
        JSONObject json = new JSONObject();
        json.put("TJRQ", usedCar.getDateApprove());
        json.put("DEPT_ID", usedCar.getDept().getId());
        json.put("DEPT_NAME", usedCar.getDept().getName());
        json.put("EMPLOYEE_ID", usedCar.getInspectorId().getId());
        json.put("EMPLOYEE_NAME", usedCar.getInspectorId().getName());
        json.put("COMPANY_ID", role.getId());
        json.put("COMPANY_NAME", role.getName());
        json.put("secondHandCommision", usedCar.getInspectorCommission());
        SpringManager.getBean(TCService.class).inspectorCommissionBySubmit(json);
    }


    /***
     * 推送计算平台服务费消息
     */

    public void pushMessageForCalculateFee(UsedCar usedCar) {
        JSONObject json = new JSONObject();
        json.put("id", usedCar.getId());

        OutboxPayloadWrapper wrapper = new OutboxPayloadWrapper();
        wrapper.setSubscriber("fn.partnerCheck.calculateUsedCarFee");
        wrapper.setAggregateId(usedCar.getId());
        wrapper.setPayload(json.toJSONString());

        SpringManager.getBean(OutboxEventService.class).sendSaveEvent(wrapper);
    }
}
